package com.bw.message.model

import android.content.Context
import android.os.Build
import android.os.Vibrator
import android.os.VibratorManager
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.DeviceUtils.isEmulator
import com.bw.lib_base.base.BaseApp.Companion.context
import com.bw.lib_base.base.BaseViewModel
import com.bw.message.entity.MessageData
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class MessageViewModel @Inject constructor(


    val messageRepo: MessageRepo,
    private val webSocketManager: WebSocketManager,
):BaseViewModel(){
    // 消息数据流
    private val  _messageData=MutableStateFlow<List<MessageData>?>( null)
    val messageData:StateFlow<List<MessageData>?> =(_messageData)


    // 初始化WebSocket连接
    init {

        // 初始化设备能力检测
       // checkDeviceCapabilities()


        webSocketManager.setMessageListener { messages ->
            viewModelScope.launch {
                _messageData.emit(messages)
            }
        }

    }

    fun getMessageData(accessId: String, userId: Int) {
        viewModelScope.launch {
            if (isInitLife()) {
                lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
                    // 先通过HTTP获取历史消息
                    val historyMessages = messageRepo.getMessage(accessId, userId)
                    _messageData.emit(historyMessages ?: emptyList())

                    // 然后建立WebSocket连接接收实时消息
                    webSocketManager.connect(
                        url = "wss://echo.websocket.org",
                        accessId = accessId,
                        userId = userId
                    )
                }
            }
        }
    }

    // 需要明确定义 disconnect 方法
    fun disconnect() {
        webSocketManager.disconnect()
    }
    fun sendMessage(message: String) {
        // 实现发送消息逻辑
        webSocketManager.webSocket?.send(message)
    }

    override fun onCleared() {
        super.onCleared()
        webSocketManager.disconnect()
    }


}